package cn.ac.siom.query.util.action;

import cn.ac.siom.query.service.IaccessService;
import cn.ac.siom.query.util.ObjectToJSON;
import cn.ac.siom.query.vo.Accessinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

public abstract class DefaultAction {
    public Logger logger = LoggerFactory.getLogger("DefaultAction");

    @Resource
    private MessageSource messageSource;

    @Resource
    private IaccessService iaccessService;
    private static DefaultAction defaultAction;

    @PostConstruct
    public void init() {
        defaultAction = this;
        defaultAction.iaccessService = this.iaccessService;
    }

    private Integer currentPage = 1; // 表单第一页
    private Integer lineSize = 2; //表示每页显示记录数

    /**
     * 每次访问接口都要存储记录
     * @param request
     * @throws Exception
     */
    public static void insertAccessinfo(HttpServletRequest request,String pageName) throws SQLException {
        Accessinfo accessinfo = new Accessinfo();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String url =request.getHeader("Referer");
        if(url==null){
            accessinfo.setUrl("/");
        }else{
            accessinfo.setUrl(url);
        }
        accessinfo.setIp(ip);
        accessinfo.setName(pageName);
        defaultAction.iaccessService.insertOne(accessinfo);
        Logger log = LoggerFactory.getLogger("DefaultAction");
        log.info("当前访问IP:"+ip+"========"+"访问的URL="+url);
    }

    /**
     * 从request中获得参数Map，并返回可读的Map
     *
     * @param request
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    public void print(HttpServletResponse response,Object msg){
        try {
            response.getWriter().print(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void handSplit(HttpServletRequest request,HttpServletResponse response){
        try {
            this.currentPage = Integer.parseInt(request.getParameter("cp"));
        }catch (Exception e){}
        try {
            this.lineSize = Integer.parseInt(request.getParameter("ls"));
        }catch (Exception e){}
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public Integer getLineSize() {
        return lineSize;
    }

    /**
     * 可以根据Key取得资源的内容
     * @param key 表示要读取key
     * @param param 表示设置的参数
     * @return
     */
    public String getResource(String key,String ...param){
        return this.messageSource.getMessage(key,param, Locale.getDefault());
    }

    /**
     * 设置提示信息与跳转路径，通过资源文件读取的
     * @param mav
     * @param msg
     * @param path
     */
    public void setMsgAndPath(ModelAndView mav,String msg,String path){
        if (mav != null){
            if (this.getText() != null){
                String [] result = this.getText().split("\\|");
                mav.addObject("msg",this.messageSource.getMessage(msg,result,Locale.getDefault()));
            }else{
                mav.addObject("msg",this.messageSource.getMessage(msg,null,Locale.getDefault()));
            }
            mav.addObject("path",this.messageSource.getMessage(path,null,Locale.getDefault()));

        }
    }

    /**
     * 将对象转换为json数据
     * @param response
     * @param vo
     */
    public void printObjectToJson(HttpServletResponse response,Object vo){
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(ObjectToJSON.convertorObjectToJSON(vo));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将list集合数据转换为json
     * @param response
     * @param name
     * @param all
     */
    public void printObjectToList(HttpServletResponse response, String name, List<?> all){
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(ObjectToJSON.convertorListToJson(name,all));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将集合数据转换为json，并实现分页处理
     * @param response
     * @param name
     * @param all
     * @param allRecorders
     */
    public void printObjectToListSplit(HttpServletResponse response,String name,List<?> all,Integer allRecorders){
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(ObjectToJSON.convertorListSplitToJson(name,all,allRecorders));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public abstract String getText();
}
